package cn.dankal.flyaudio.friend;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ContractPersonAdapter;
import cn.dankal.flyaudio.entity.GroupEntity;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.dankal.flyaudio.view.LetterNavView;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetGroupInfoCallback;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

public class ChangeGroupOwnerActivity extends BaseActivity {

    private RecyclerView friendView;
    private LetterNavView navView;
    private ImageView rightIcon;
    private TextView rightText;
    private TextView titleView;
    private View newFriendView;
    private View newFriendLineView;
    private View groupView;
    private MultipleStatusView statusView;

    private ContractPersonAdapter adapter;

    private List<GroupEntity> personEntities = new ArrayList<>();

    List<GroupEntity> groupEntities = new ArrayList<>();

    private Long groupId;

    private GroupInfo mGroupInfo;
    private AppCompatTextView tvPrompt;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contract_person;
    }

    @Override
    protected void initComponents() {
        friendView = findViewById(R.id.rv_friend);
        rightIcon = findViewById(R.id.iv_friend_add);
        groupId = getIntent().getLongExtra("group_id", 0);
        navView = findViewById(R.id.letter_container);
        rightText = findViewById(R.id.tv_confirm);
        groupView = findViewById(R.id.rl_group_layout);
        newFriendView = findViewById(R.id.rl_new_friend_layout);
        newFriendLineView = findViewById(R.id.rl_new_friend_line);
        tvPrompt = findViewById(R.id.tv_prompt);
        groupView.setVisibility(View.GONE);
        newFriendLineView.setVisibility(View.GONE);
        newFriendView.setVisibility(View.GONE);
        titleView = findViewById(R.id.tv_title);
        rightIcon.setVisibility(View.GONE);
        rightText.setVisibility(View.VISIBLE);
        rightText.setEnabled(false);
        titleView.setText("群管理");
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initSearch();
//        personEntities.addAll(TestData.getContractPerson());
        friendView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContractPersonAdapter(this, personEntities);
        adapter.setPickModel(ContractPersonAdapter.MODEL_PICK);
        adapter.setSinglePick(true);
        friendView.setAdapter(adapter);
        navView.setLetterChangeListener(new LetterNavView.LetterChangeListener() {
            @Override
            public void onTouchingLetterChanged(int index, String text) {
                int count = 0;
                for (int i = 0; i < index; i++) {
                    count++;
                    if (personEntities.isEmpty()) {
                        return;
                    }
                    count += personEntities.get(i).getChildren().size();
                }
                if (count != -1) {
                    friendView.scrollToPosition(count);
                    LinearLayoutManager mLayoutManager =
                            (LinearLayoutManager) friendView.getLayoutManager();
                    mLayoutManager.scrollToPositionWithOffset(count, 0);
                }
//                friendView.scrollToPosition(count);
            }
        });
        adapter.setOnItemSelectListener(new ContractPersonAdapter.OnItemSelectListener() {
            @Override
            public void onSelect(List<UserInfo> userInfos) {
                if (userInfos.isEmpty()) {
                    rightText.setEnabled(false);
                    rightText.setClickable(false);
                    tvPrompt.setVisibility(View.GONE);
                } else {
                    rightText.setEnabled(true);
                    rightText.setClickable(true);
                    tvPrompt.setVisibility(View.VISIBLE);
                }
            }
        });
        JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
            @Override
            public void gotResult(int i, String s, GroupInfo groupInfo) {
                mGroupInfo = groupInfo;
                handleFriend(groupInfo.getGroupMembers());
            }
        });
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGroupInfo.changeGroupAdmin(adapter.getPickMember().get(0).getUserName(), adapter.getPickMember().get(0).getAppKey(), new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        LiveEventBus.get(LiveDataBusConstants.UPDATE_GROUP_MEMBERS_INFO, String.class).post("1");
                        ToastUtils.showShort("移交成功");
                        finish();
                    }
                });
            }
        });
    }

    private TextView searchTextView;

    private ClearEditText searchEditText;

    private void initSearch() {
        statusView = findViewById(R.id.multiple_status_view);
        searchTextView = findViewById(R.id.tv_search);
        searchEditText = findViewById(R.id.et_search);
        searchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = searchEditText.getText().toString();
                if (TextUtils.isEmpty(key)) return;
                doSearch(key);
            }
        });
        searchEditText.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (TextUtils.isEmpty(keyword)) return;
                doSearch(keyword);
            }
        });
        searchEditText.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (TextUtils.isEmpty(s)) {
                    friendView.setAdapter(adapter);
                    statusView.showContent();
                }
            }
        });
        statusView.showContent();
    }

    private List<UserInfo> friendList = new ArrayList<>();

    private void doSearch(String key) {
        List<UserInfo> searResult = new ArrayList<>();
        for (UserInfo userInfo : friendList) {
            ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                    .get(userInfo.getNickname());
            StringBuilder sb = new StringBuilder();
            if (tokens != null && tokens.size() > 0) {
                for (HanziToPinyin.Token token : tokens) {
                    if (token.type == HanziToPinyin.Token.PINYIN) {
                        sb.append(token.target);
                    } else {
                        sb.append(token.source);
                    }
                }
            }
            if (sb.toString().contains(key) || userInfo.getNickname().contains(key)) {
                searResult.add(userInfo);
            }
        }
        if (searResult.isEmpty()) {
            statusView.showEmpty();
        }else{
            handleFriend(searResult);
        }
    }

    private void handleFriend(List<UserInfo> list) {
        groupEntities.clear();
        friendList.clear();
        friendList.addAll(list);
        for (UserInfo userInfo : list) {
            if (!userInfo.getNickname().equals(JMessageClient.getMyInfo().getNickname())) {
                String letter = getLetter(userInfo.getNickname());
                if (!checkGroupSave(letter)) {
                    GroupEntity groupEntity = new GroupEntity();
                    groupEntity.setHeader(letter);
                    groupEntities.add(groupEntity);
                }
                GroupEntity groupEntity = getGroupByLetter(letter);
                if (groupEntity != null) {
                    List<UserInfo> userInfos = groupEntity.getChildren();
                    userInfos.add(userInfo);
                    groupEntity.setChildren(userInfos);
                }
            }
        }
        adapter.setNewData(groupEntities);
    }

    private boolean checkGroupSave(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return true;
            }
        }
        return false;
    }

    private GroupEntity getGroupByLetter(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return entity;
            }
        }
        return null;
    }

    private String getLetter(String name) {
        String letter;
        ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                .get(name);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanziToPinyin.Token token : tokens) {
                if (token.type == HanziToPinyin.Token.PINYIN) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        String sortString = sb.toString().substring(0, 1).toUpperCase();
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase();
        } else {
            letter = "#";
        }
        return letter;
    }
}
